package com.link2room.blaster.facade.impl;

import com.link2room.blaster.constant.MsgConstant;
import com.link2room.blaster.dto.param.base.RegistrationVerificationBaseParamDto;
import com.link2room.blaster.common.FreemarkerUtil;
import com.link2room.blaster.facade.IRegistrationVerificationFacadeService;
import com.link2room.blaster.service.IMsgTemplateService;
import com.link2room.common.enums.BaseSysExceptionEnum;
import com.link2room.common.exception.SysException;
import com.link2room.common.redis.RedisUtil;
import com.link2room.common.service.ICommonService;
import com.link2room.common.util.MD5Util;
import com.link2room.common.util.StringUtil;
import com.link2room.blaster.dto.result.api.RegistrationVerificationResDto;
import com.link2room.blaster.entity.DayuOption;
import com.link2room.blaster.entity.MsgTemplate;
import com.link2room.enums.exception.BlasterSysExceptionEnum;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 使用SMSCodeFacadeServiceImpl
 * Created by Nakisa on 2016/10/27.
 */
@Component("registrationVerificationFacadeService")
@Deprecated
public class RegistrationVerificationFacadeServiceImpl implements IRegistrationVerificationFacadeService {
    @Resource
    private ICommonService commonServiceSupport;
    @Resource
    private IMsgTemplateService msgTemplateService;
    @Resource
    private RedisUtil redisUtil;
    @Override
    public RegistrationVerificationResDto sendSignupVerificationCode(RegistrationVerificationBaseParamDto paramDto) throws Exception {
        String hotelGroupCode = paramDto.getLhotelGroupCode();
        String phone = paramDto.getPhone();
        if(!isMobiPhoneNum(phone)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(), BaseSysExceptionEnum.INVALID_PARA.getMsg()+"电话号码不合法", BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
        if(StringUtil.isBlank(hotelGroupCode)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(), BaseSysExceptionEnum.INVALID_PARA.getMsg()+"[hotelGroupCode]:"+hotelGroupCode, BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
        //生成验证码
        String verificationCode = random();
        //发送验证短信
        sendMsg(verificationCode,phone,hotelGroupCode);
        RegistrationVerificationResDto res = new RegistrationVerificationResDto();
        // 缓存验证码，生成msgId并返回，返回给用户用于验证
        String msgId = cacheVerificationCode(verificationCode, phone,hotelGroupCode);
        res.setMsgId(msgId);
        return res;

    }

    @Override
    public void signupVerifyCode(RegistrationVerificationBaseParamDto paramDto) {
        String verificationCode = paramDto.getVerificationCode();
        String hotelGroupCode = paramDto.getLhotelGroupCode();
        String phone = paramDto.getPhone();
        if(!isMobiPhoneNum(phone)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(), BaseSysExceptionEnum.INVALID_PARA.getMsg()+"电话号码不合法", BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
        if(StringUtil.isBlank(hotelGroupCode)){
            throw new SysException(BaseSysExceptionEnum.INVALID_PARA.getCode(), BaseSysExceptionEnum.INVALID_PARA.getMsg()+"[hotelGroupCode]:"+hotelGroupCode, BaseSysExceptionEnum.INVALID_PARA.getBizType());
        }
        //生成msgId
        String msgId = getMsgId(phone,hotelGroupCode);
        //查询
        if(!redisUtil.exists(msgId)){
            throw new SysException(BlasterSysExceptionEnum.VERIFICATIONCODE_OVERDUE.getCode(),
                    BlasterSysExceptionEnum.VERIFICATIONCODE_OVERDUE.getMsg()+"msgId:"+msgId,
                    BlasterSysExceptionEnum.VERIFICATIONCODE_OVERDUE.getBizType());
        }else{
            String cacheCode = (String) redisUtil.get(msgId);
            if(!cacheCode.equals(verificationCode)){
                throw new SysException(BlasterSysExceptionEnum.VERIFICATIONCODE_ERROR.getCode(),
                        BlasterSysExceptionEnum.VERIFICATIONCODE_ERROR.getMsg()+"msgId:"+msgId,
                        BlasterSysExceptionEnum.VERIFICATIONCODE_ERROR.getBizType());
            }
        }
    }

    /**
     * 缓存验证码，生成msgId并返回，返回给用户用于验证
     * msgId 根据手机号码和集团md5生成，每次缓存会把原来的缓存覆盖
     * @param verificationCode
     * @return
     */
    private String cacheVerificationCode(String verificationCode,String phone,String hotelGroupCode){

        String msg = getMsgId(phone,hotelGroupCode);
        //1天有效
        redisUtil.set(msg,verificationCode,86400L);
        return msg;
    }

    private String getMsgId(String phone,String hotelGroupCode){

        return "msgId-"+MD5Util.getMd5(phone+hotelGroupCode) ;
    }

    private void sendMsg(String verificationCode,String phone,String lhotelGroupCode) throws Exception {

        DayuOption dy = getDayuOption(lhotelGroupCode);
        String appkey = dy.getAppkey();
        String secret = dy.getSecret();
        String url = dy.getUrl();
        //获得模板
        MsgTemplate template = msgTemplateService.findTemplate(lhotelGroupCode, null, MsgConstant.CHANNEL.DAYU, MsgConstant.TEMPLET_CODE.Registration_Verification);
        TaobaoClient client = new DefaultTaobaoClient(url, appkey, secret);
        AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        req.setSmsType("normal");
        req.setSmsFreeSignName(template.getDayuSignName());//短信签名
        Map map = new HashMap<>();
        map.put("code",verificationCode);
        String str = FreemarkerUtil.getMsg(template,map );
        req.setSmsParamString(str);
        req.setRecNum(phone);
        req.setSmsTemplateCode(template.getTemplateId());
        AlibabaAliqinFcSmsNumSendResponse rsp = client.execute(req);
        if(StringUtil.isNotBlank(rsp.getErrorCode())){
            throw new SysException(BlasterSysExceptionEnum.DAYU_SDK_ERROR.getCode(), BlasterSysExceptionEnum.DAYU_SDK_ERROR.getMsg()+rsp.getBody()+":"+str+" ，"+template.getTemplateId(), BlasterSysExceptionEnum.DAYU_SDK_ERROR.getBizType());
        }
    }

    private DayuOption getDayuOption(String lhotelGroupCode) throws Exception {
        //查找出大于配置
        DayuOption dayuOpt = new DayuOption();
        dayuOpt.setLhotelGroupCode(lhotelGroupCode);
        DayuOption dy = commonServiceSupport.findOneEQ(DayuOption.class, dayuOpt);
        if(dy==null){
            throw new SysException(BlasterSysExceptionEnum.NO_DAYU_OPT.getCode(), BlasterSysExceptionEnum.NO_DAYU_OPT.getMsg()+"lhotelGroupCode:"+lhotelGroupCode, BlasterSysExceptionEnum.NO_DAYU_OPT.getBizType());
        }
        return dy;
    }

    /**
     * 电话号码判断
     * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
     *联通：130、131、132、152、155、156、185、186
     *电信：133、153、180、189、（1349卫通）
     * @param telNum
     * @return
     */
    private boolean isMobiPhoneNum(String telNum){
        String regex = "^(1[3456789])\\d{9}$";
        Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(telNum);
        return m.matches();
    }

    /**
     * 生成6位数字验证码
     * @return
     */
    private String random(){
        Random random = new Random();
        String result="";
        for(int i=0;i<6;i++) {
            result += random.nextInt(10);
        }
        System.out.println(result);
        return result;
    }
}
